<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\DictTypeRequest;
use App\Models\SysDictType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SysDictTypeController extends ApiBaseController
{
    public function index(Request $request){
        $paginator = SysDictType::filter($request->all())->paginate($this->pageSize);
        return success(page_format($paginator));
    }

    public function show(Request $request, SysDictType $model){
        $id = $request->get('id');
        $data = $model->find($id);
        return success(['data' => $data->toArray()]);
    }

    public function create(DictTypeRequest $request){
        $validated = $request->validated();
        $model = SysDictType::create($validated);
        return success([],'添加成功');
    }

    public function update(DictTypeRequest $request, SysDictType $model)
    {
        $id = $request->post('id');
        $sysDictType = $model->find($id);
        $validated = $request->validated();

        if($sysDictType){
            $sysDictType->update($validated);
        }else{
            return error('数据不存在');
        }

        return success([],'更新成功');
    }

    public function destroy($ids, Request $request, SysDictType $model){
        $id_arr = explode(',', $ids);
        DB::transaction(function () use ($id_arr, $model) {
            $dict_types = SysDictType::whereIn('id',$id_arr)->pluck('dict_type');
            $model->destroy($id_arr);
            DB::table('sys_dict_data')->whereIn('dict_type', $dict_types)->delete();
        });
        $model->destroy($id_arr);
    }

    public function refreshCache(){

    }

}
